import axios from 'axios'

// 缓存请求
export const keepPromise = {
  data: {},
  set(key, data) {
    this.data[key] = data
  },
  get(key) {
    return this.data[key]
  },
  clear(key) {
    delete this.data[key]
  },
}

/**
 * 缓存适配器
 * 配置全局缓存
 * Axios.create({adapter: KeepPromise({keepTime:5000})});
 * 使用方式：指定接口是否缓存
 * _axios.post(url,formData,config:{keepCache:true,keepTime:5000})
 *
 *
 */
export default ({keepTime = 0} = {}) => async config => {
  //解决url中带时间戳
  config.url = config.url.replace(/t=\d+&?/, '')
  const cacheKey = config.method + ":" + config.url

  let hasCache = config.keepCache
  keepTime=config.keepTime||keepTime
  let responsePromise = hasCache ? keepPromise.get(cacheKey) : undefined
  if (!responsePromise) {
    responsePromise = (async () => {
      try {
        const response = await axios.defaults.adapter(config)
        return Promise.resolve(response)
      } catch (reason) {
        keepPromise.clear(cacheKey)
        return Promise.reject(reason)

      }
    })()
    if (hasCache) {
      if (keepTime > 0) {
        keepPromise.set(cacheKey, responsePromise)
        setTimeout(() => {
          keepPromise.clear(cacheKey)
        }, keepTime)
      }
    }
  }
  // 为防止数据源污染
  return responsePromise.then(data => JSON.parse(JSON.stringify(data)))
}
